import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getKeyList } from "@pureadmin/utils";
import { usePublicHooks } from "@/views/system/hooks";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, toRaw } from "vue";
import { GridifyQueryBuilder, ConditionalOperator as op } from "gridify-client";
import { queryOperationLogs, batchDeleteLog } from "@/swagger/api/monitor";


export function useRole(tableRef: Ref) {
  const form = reactive({
    module: "",
    status: "",
    operatingTime: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const { tagStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "序号",
      prop: "id",
      minWidth: 90
    },
    {
      label: "操作人员",
      prop: "userName",
      minWidth: 100
    },
    {
      label: "所属模块",
      prop: "module",
      minWidth: 140
    },
    {
      label: "操作概要",
      prop: "operation",
      minWidth: 140
    },
    {
      label: "操作 IP",
      prop: "clientIP",
      minWidth: 100
    },
    {
      label: "操作地点",
      prop: "address",
      minWidth: 140
    },
    {
      label: "操作系统",
      prop: "os",
      minWidth: 100
    },
    {
      label: "浏览器类型",
      prop: "browser",
      minWidth: 100
    },
    {
      label: "操作状态",
      prop: "statusCode",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.statusCode === 200)}>
          {row.statusCode === 200 ? "成功" : "失败"}
        </el-tag>
      )
    },
    {
      label: "操作时间",
      prop: "timeStamp",
      minWidth: 180,
      formatter: ({ timeStamp }) =>
        dayjs(timeStamp).format("YYYY-MM-DD HH:mm:ss")
    }
  ];

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
    onSearch();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  async function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    await batchDeleteLog({
      ids: getKeyList(curSelected, "id")
    }).then(() => {
      message(`已删除序号为 ${getKeyList(curSelected, "id")} 的数据`, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    });
  }

  /** 清空日志 */
  async function clearAll() {
    await batchDeleteLog({
      ids: [0]
    }).then(() => {
      message("已删除所有操作日志数据", {
        type: "success"
      });
      onSearch();
    });
  }

  async function onSearch() {
    loading.value = true;
    const query = new GridifyQueryBuilder()
      .setPage(pagination.currentPage)
      .setPageSize(pagination.pageSize)
      .addOrderBy("id", true)
      .addCondition("module", op.Contains, form.module);


    if (form.status === '200') {
      query.and().addCondition("exception", op.Equal, null);
    } else if (form.status === '500') {
      query.and().addCondition("exception", op.NotEqual, null);
    }

    if (form.operatingTime) {
      const start = (new Date(form.operatingTime[0])).toLocaleString();
      const end = (new Date(form.operatingTime[1])).toLocaleString();
      query.and().addCondition("timeStamp", op.GreaterThanOrEqual, start);
      query.and().addCondition("timeStamp", op.LessThanOrEqual, end);
    }

    const queryBuilder = query.build() as any;
    const { data } = await queryOperationLogs(queryBuilder) as any;

    dataList.value = data.items;
    pagination.total = data.totalItems;
    pagination.currentPage = data.currentPage;

    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    clearAll,
    resetForm,
    onbatchDel,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
